<template>
  <div class="flight-time-container">
    <el-card shadow="hover" class="main-card">
      <template #header>
        <div class="card-header">
          <h2>航班时间管理</h2>
          <div class="search-bar">
            <el-input
              v-model="searchForm.flightNumber"
              placeholder="请输入航班号"
              clearable
              style="width: 200px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
            <el-button type="primary" @click="handleSearch" class="action-button">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="resetSearch" class="action-button">
              <el-icon><Refresh /></el-icon>
              重置
            </el-button>
            <el-button
              type="primary"
              @click="showAddDialog"
              v-if="isSuperAdmin"
              class="action-button"
            >
              添加航班时间
            </el-button>
          </div>
        </div>
      </template>

      <div class="table-wrapper">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="loading"
          @sort-change="handleSortChange"
          highlight-current-row
          :height="tableHeight"
        >
          <!-- 表格列定义保持不变 -->
          <el-table-column prop="FLNO" label="航班号" min-width="120" sortable="custom" align="center" />
          <el-table-column prop="FIDE" label="航班标识" min-width="180" align="center" />
          <el-table-column prop="FPTT" label="计划起飞时间" min-width="180" sortable="custom" align="center">
            <template #default="{ row }">
              {{ formatDisplayTime(row.FPTT) }}
            </template>
          </el-table-column>
          <el-table-column prop="FPLT" label="计划降落时间" min-width="180" sortable="custom" align="center">
            <template #default="{ row }">
              {{ formatDisplayTime(row.FPLT) }}
            </template>
          </el-table-column>
          <el-table-column prop="STAT" label="状态" min-width="120" align="center">
            <template #default="{ row }">
              <el-tag :type="getStatusType(row.STAT)" effect="light">
                {{ row.STAT || '正常' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" align="center" fixed="right" v-if="$store.getters.currentRole === 'admin'">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button type="primary" size="small" @click="handleEdit(row)" plain>编辑</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <div class="pagination-container" :class="{ 'sticky-pagination': tableData.length >= pageSize }">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="50%">
      <el-form :model="timeForm" :rules="rules" ref="timeFormRef" label-width="100px">
        <el-form-item label="航班号" prop="FLNO">
          <el-input v-model="timeForm.FLNO" placeholder="例如：CA1234" />
        </el-form-item>
        <el-form-item label="航班标识" prop="FIDE">
          <el-input v-model="timeForm.FIDE" placeholder="例如：CZ-3126-20170601214500-A" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划起飞时间" prop="FPTT">
              <el-date-picker
                v-model="timeForm.FPTT"
                type="datetime"
                placeholder="选择计划起飞时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划降落时间" prop="FPLT">
              <el-date-picker
                v-model="timeForm.FPLT"
                type="datetime"
                placeholder="选择计划降落时间"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="状态" prop="STAT">
          <el-select v-model="timeForm.STAT" placeholder="请选择状态" style="width: 100%">
            <el-option label="正常" value="正常" />
            <el-option label="延误" value="延误" />
            <el-option label="取消" value="取消" />
            <el-option label="ONR" value="ONR" />
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 对话框按钮修改 -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false" class="action-button">取 消</el-button>
          <el-button type="primary" @click="submitForm" class="action-button">确 认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { FlightApi } from '@/api/flight'
import { Search, Refresh } from '@element-plus/icons-vue'

const store = useStore()

// 搜索表单
const searchForm = ref({ flightNumber: '' })

// 表格数据
const tableData = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10) // 修改为每页显示10条
const total = ref(0)
const sortProp = ref('')
const sortOrder = ref('')

// 状态标签类型
const getStatusType = (status) => {
  if (!status) return 'success'
  const statusStr = status.toString().toLowerCase()
  switch (statusStr) {
    case '延误':
      return 'warning'
    case '取消':
      return 'danger'
    case 'onr':
      return 'info'
    default:
      return 'success'
  }
}

// 表单数据
const timeForm = ref({
  FLNO: '',
  FIDE: '',
  FPTT: '',
  FPLT: '',
  STAT: ''
})

const dialogVisible = ref(false)
const isAdd = ref(true)
const timeFormRef = ref(null)
const isSuperAdmin = computed(() => store.getters.isSuperAdmin)
const dialogTitle = computed(() => (isAdd.value ? '添加航班时间' : '编辑航班时间'))

const rules = {
  FLNO: [{ required: true, message: '请输入航班号', trigger: 'blur' }],
  FIDE: [{ required: true, message: '请输入航班标识', trigger: 'blur' }],
  FPTT: [{ required: true, message: '请选择计划起飞时间', trigger: 'change' }],
  FPLT: [{ required: false, message: '请选择计划降落时间', trigger: 'change' }],
  STAT: [{ required: true, message: '请选择状态', trigger: 'change' }]
}

// 格式化日期为 YYYYMMDDHHmmss
const formatDateTime = (date) => {
  if (!date) return ''
  const d = new Date(date)
  const year = d.getFullYear()
  const month = String(d.getMonth() + 1).padStart(2, '0')
  const day = String(d.getDate()).padStart(2, '0')
  const hours = String(d.getHours()).padStart(2, '0')
  const minutes = String(d.getMinutes()).padStart(2, '0')
  const seconds = String(d.getSeconds()).padStart(2, '0')
  return `${year}${month}${day}${hours}${minutes}${seconds}`
}

// 加载数据
const fetchData = async () => {
  try {
    loading.value = true
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      flightNumber: searchForm.value.flightNumber
    }

    // 添加排序参数
    if (sortProp.value && sortOrder.value) {
      params.sortField = sortProp.value
      params.sortOrder = sortOrder.value === 'ascending' ? 'asc' : 'desc'
    }

    const response = searchForm.value.flightNumber
      ? await FlightApi.getFlightTimesByNumber(searchForm.value.flightNumber, currentPage.value, pageSize.value)
      : await FlightApi.getFlightTimes(currentPage.value, pageSize.value)

    if (response.data) {
      tableData.value = response.data || []
      total.value = response.totalRecords || 0
    }
  } catch (error) {
    ElMessage.error('获取航班时间数据失败: ' + error.message)
    console.error('获取航班时间数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value.flightNumber = ''
  currentPage.value = 1
  fetchData()
}

// 分页变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 排序变化
const handleSortChange = ({ prop, order }) => {
  sortProp.value = prop
  sortOrder.value = order
  fetchData()
}

// 显示添加对话框
const showAddDialog = () => {
  isAdd.value = true
  timeForm.value = {
    FLNO: '',
    FIDE: '',
    FPTT: '',
    FPLT: '',
    STAT: ''
  }
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  isAdd.value = false
  timeForm.value = { ...row }
  dialogVisible.value = true
}

// 新增格式化显示时间的方法
const formatDisplayTime = (timeStr) => {
  if (!timeStr) return '-'

  // 假设原始格式是YYYYMMDDHHmmss
  if (timeStr.length === 14) {
    const year = timeStr.substring(0, 4)
    const month = timeStr.substring(4, 6)
    const day = timeStr.substring(6, 8)
    const hour = timeStr.substring(8, 10)
    const minute = timeStr.substring(10, 12)
    return `${year}-${month}-${day} ${hour}:${minute}`
  }

  // 如果是其他格式，尝试解析为Date对象
  try {
    const date = new Date(timeStr)
    if (isNaN(date.getTime())) return timeStr // 如果解析失败，返回原始值

    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      hour12: false
    }).replace(/\//g, '-')
  } catch {
    return timeStr
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await timeFormRef.value.validate()

    // 检查时间是否有效
    if (isNaN(new Date(timeForm.value.FPTT).getTime())) {
      ElMessage.error('计划起飞时间格式不正确')
      return
    }
    if (timeForm.value.FPLT && isNaN(new Date(timeForm.value.FPLT).getTime())) {
      ElMessage.error('计划降落时间格式不正确')
      return
    }

    const dto = {
      flno: timeForm.value.FLNO,
      fide: timeForm.value.FIDE,
      stat: timeForm.value.STAT,
      fptt: formatDateTime(timeForm.value.FPTT),
      fplt: formatDateTime(timeForm.value.FPLT)
    }

    if (isAdd.value) {
      await axios.post('http://localhost:8081/flightUpdate/addTimeInfo', dto)
      ElMessage.success('添加成功')
    } else {
      await axios.put('http://localhost:8081/flightUpdate/updateTimeInfo', dto)
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
    fetchData()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败，请检查输入或网络连接')
    }
  }
}

// 初始化加载数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.flight-time-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 64px);
}

.main-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: 100%;
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.card-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.search-bar .el-input {
  width: 200px;
}

.table-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
}

.el-table {
  flex: 1;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  background: #fff;
  border-top: 1px solid var(--el-border-color-light);
}

.pagination-container.sticky-pagination {
  position: sticky;
  bottom: 0;
  z-index: 1;
  background: #fff;
}

.action-button {
  white-space: nowrap;
  padding: 8px 15px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.dialog-footer {
  text-align: right;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .search-bar {
    gap: 8px;
  }
  .search-bar .el-input {
    width: 180px;
  }
}

@media (max-width: 992px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .search-bar {
    width: 100%;
    flex-wrap: wrap;
  }

  .search-bar .el-input {
    width: calc(50% - 5px);
  }

  .action-button {
    flex: 1;
  }
}

@media (max-width: 768px) {
  .pagination-container {
    width: 100%;
    overflow-x: auto;
  }

  .el-pagination {
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .el-pagination :deep(.el-pagination__total),
  .el-pagination :deep(.el-pagination__sizes),
  .el-pagination :deep(.el-pagination__jump) {
    margin: 5px 0;
    width: 100%;
    justify-content: flex-end;
  }
}

@media (max-width: 576px) {
  .flight-time-container {
    padding: 10px;
  }

  .search-bar .el-input {
    width: 100%;
  }

  .action-button {
    width: 100%;
  }

  .el-pagination :deep(.btn-prev),
  .el-pagination :deep(.btn-next),
  .el-pagination :deep(.more) {
    display: none;
  }

  .action-buttons {
    flex-direction: column;
    gap: 5px;
  }

  .action-buttons .el-button {
    width: 100%;
  }
}
</style>
